using System.Diagnostics;
using System.Security.Principal;

namespace Toolbox.Common
{
    /// <summary>
    /// 管理员权限工具类
    /// 作者：huobing
    /// </summary>
    public static class AdminUtilities
    {
        /// <summary>
        /// 检查当前程序是否以管理员身份运行
        /// </summary>
        /// <returns>如果是管理员身份运行返回true，否则返回false</returns>
        public static bool IsRunningAsAdministrator()
        {
            try
            {
                using WindowsIdentity identity = WindowsIdentity.GetCurrent();
                WindowsPrincipal principal = new(identity);
                return principal.IsInRole(WindowsBuiltInRole.Administrator);
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 以管理员身份重启当前应用程序
        /// </summary>
        /// <param name="arguments">启动参数（可选）</param>
        /// <returns>操作是否成功</returns>
        public static bool RestartAsAdministrator(string arguments = "")
        {
            try
            {
                // 获取当前应用程序的路径
                string currentAppPath = Application.ExecutablePath;

                // 创建新的进程启动信息
                ProcessStartInfo startInfo = new()
                {
                    UseShellExecute = true,
                    WorkingDirectory = Environment.CurrentDirectory,
                    FileName = currentAppPath,
                    Verb = "runas", // 请求管理员权限
                    Arguments = arguments
                };

                // 启动新进程
                Process.Start(startInfo);

                // 关闭当前应用程序
                Application.Exit();
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"无法以管理员身份重启应用程序: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        /// <summary>
        /// 以管理员身份运行指定程序
        /// </summary>
        /// <param name="executablePath">可执行文件路径</param>
        /// <param name="arguments">启动参数（可选）</param>
        /// <param name="workingDirectory">工作目录（可选）</param>
        /// <returns>操作是否成功</returns>
        public static bool RunAsAdministrator(string executablePath, string arguments = "", string? workingDirectory = null)
        {
            try
            {
                ProcessStartInfo startInfo = new()
                {
                    UseShellExecute = true,
                    FileName = executablePath,
                    Verb = "runas", // 请求管理员权限
                    Arguments = arguments
                };

                if (!string.IsNullOrEmpty(workingDirectory))
                {
                    startInfo.WorkingDirectory = workingDirectory;
                }

                Process.Start(startInfo);
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"无法以管理员身份运行程序 {executablePath}: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        /// <summary>
        /// 执行需要管理员权限的命令
        /// </summary>
        /// <param name="command">要执行的命令</param>
        /// <param name="arguments">命令参数</param>
        /// <returns>命令执行结果</returns>
        public static async Task<CommandResult> ExecuteCommandAsAdminAsync(string command, string arguments = "")
        {
            CommandResult result = new()
            {
                Command = command,
                Arguments = arguments,
                StartTime = DateTime.Now
            };

            try
            {
                ProcessStartInfo startInfo = new()
                {
                    FileName = command,
                    Arguments = arguments,
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true,
                    Verb = "runas" // 请求管理员权限
                };

                using Process process = new() { StartInfo = startInfo };
                _ = process.Start();
                result.Output = await process.StandardOutput.ReadToEndAsync();
                result.Error = await process.StandardError.ReadToEndAsync();
                await process.WaitForExitAsync();
                result.ExitCode = process.ExitCode;
                result.EndTime = DateTime.Now;
                result.IsSuccess = process.ExitCode == 0;
            }
            catch (Exception ex)
            {
                result.Error = ex.Message;
                result.IsSuccess = false;
                result.EndTime = DateTime.Now;
            }

            return result;
        }
    }

    /// <summary>
    /// 命令执行结果类
    /// 作者：huobing
    /// </summary>
    public class CommandResult
    {
        /// <summary>
        /// 执行的命令
        /// </summary>
        public string Command { get; set; } = string.Empty;

        /// <summary>
        /// 命令参数
        /// </summary>
        public string Arguments { get; set; } = string.Empty;

        /// <summary>
        /// 标准输出
        /// </summary>
        public string Output { get; set; } = string.Empty;

        /// <summary>
        /// 错误输出
        /// </summary>
        public string Error { get; set; } = string.Empty;

        /// <summary>
        /// 退出代码
        /// </summary>
        public int ExitCode { get; set; }

        /// <summary>
        /// 是否成功执行
        /// </summary>
        public bool IsSuccess { get; set; }

        /// <summary>
        /// 开始执行时间
        /// </summary>
        public DateTime StartTime { get; set; }

        /// <summary>
        /// 执行结束时间
        /// </summary>
        public DateTime? EndTime { get; set; }

        /// <summary>
        /// 执行耗时（毫秒）
        /// </summary>
        public double ElapsedMilliseconds => EndTime.HasValue ? (EndTime.Value - StartTime).TotalMilliseconds : 0;
    }
}